import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import requests
import base64
import json
import baiduocr as ocr
def login(url, user,passs,driver):
    # 打开网页
    driver.get(url)
    # 等待页面加载完成
    time.sleep(2) 
    # 使用WebDriverWait等待直到包含特定文本的元素出现
    wait = WebDriverWait(driver, 10)  # 最多等待10秒
    input_element = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='输入账号']")))
    input_element.send_keys(user)
    wait = WebDriverWait(driver, 10)  # 最多等待10秒
    input_element = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='输入密码']")))
    input_element.send_keys(passs)
    GetCode(driver,url)
    return 1 
def GetCode(driver,url):
    wait = WebDriverWait(driver, 10)  # 最多等待10秒
    element = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[text()='刷新验证码']")))
    # 点击元素
    element.click()
    time.sleep(3)
    code_elements = driver.find_elements(By.CLASS_NAME, 'code')
    image_name="downloaded_images/"
    # 创建一个目录来保存图片
    download_dir = 'downloaded_images'
    if not os.path.exists(download_dir):
        os.makedirs(download_dir)
    # 遍历每个code元素
    for code_element in code_elements:
        # 在每个code元素内部找到所有的img标签
        images = code_element.find_elements(By.TAG_NAME, 'img')
        # 下载这些图片
        for index, img in enumerate(images):
            src = img.get_attribute('src')
            if src:
                try:
                    if src and src.startswith('data:image'):
                        base64_data = src.split(',')[1]
                            # 解码Base64数据
                        image_data = base64.b64decode(base64_data)
                            # 生成图片文件名
                        file_name = f"image_{index + 1}.png"
                        file_path = os.path.join(download_dir, file_name)
                        image_name=download_dir+"/"+file_name
                            # 保存图片到本地
                        with open(file_path, 'wb') as file:
                                file.write(image_data)
                        print(f"Downloaded: {file_path}")
                    else:
                    # 发送HTTP请求下载图片
                        response = requests.get(src)
                        if response.status_code == 200:
                            # 生成图片文件名
                            file_name = f"image_{index + 1}.jpg"
                            file_path = os.path.join(download_dir, file_name)
                            image_name=download_dir+"/"+file_name
                            # 保存图片到本地
                            with open(file_path, 'wb') as file:
                                file.write(response.content)
                            print(f"Downloaded: {file_path}")
                        else:
                            print(f"Failed to download image from {src}")
                except Exception as e:
                    print(f"Error downloading image from {src}: {e}")
    with open(image_name, 'rb') as f:
        image = base64.b64encode(f.read())
    # 使用百度文字识别API请求文字识别
    response =ocr.TextOCR(image)
    code=response["words_result"][0]["words"]
    # 等待输入框出现
    wait = WebDriverWait(driver, 10)
    input_element = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='输入验证码']")))
    input_element.clear()
    input_element.send_keys(code)
    element = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[text()='登录']")))
    element.click()
    time.sleep(5)
    if driver.current_url == url:  # 假设登录失败后仍然停留在登录页面
         GetCode(driver,url)
    return
    
